package com.lagou.servlet;

import com.lagou.bean.User;
import com.lagou.service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "CheckLoginServlet", value = "/CheckLoginServlet")
public class CheckLoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1.获取Cookie中的用户名和密码
        Cookie[] cookies = request.getCookies();
        String userName = null;
        String password = null;
        for (Cookie cookie : cookies) {
            String cookieName = cookie.getName();
            String cookieValue = cookie.getValue();
            if (cookieName.equals("userName")) {
                userName = cookieValue;
            } else if (cookieName.equals("password")) {
                password = cookieValue;
            }
        }
        System.out.println(userName);
        System.out.println(password);
        // 2.创建UserService类型的对象去实现数据的校验功能
        UserService userService = new UserService();
        User user = userService.loginUserService(new User(userName, password));
        if(null==user){
            //验证失败跳转到登陆界面
            response.sendRedirect("login.jsp");
        }else{
            //3.验证成功,向session内存入一条数据
            request.getSession().setAttribute("login","login");
            //跳转到主界面
            response.sendRedirect("main.jsp");
        }
    }
}
